Wildcard Matching

Implement wildcard pattern matching with support for '?' and '*'.

  1. '?' Matches any single character.
  2. '*' Matches any sequence of characters (including the empty sequence).
  3. The matching should cover the entire input string (not partial).
  4. The function prototype should be:
  5. bool isMatch(const char *s, const char *p)
  6. Some examples:
  7. isMatch("aa","a") false
  8. isMatch("aa","aa") true
  9. isMatch("aaa","aa") false
  10. isMatch("aa", "*") true
  11. isMatch("aa", "a*") true
  12. isMatch("ab", "?*") true
  13. isMatch("aab", "c*a*b") false

Solution:

  1. public class Solution {
  2. public boolean isMatch(String s, String p) {
  3. int n = s.length(), m = p.length();
  4. boolean[][] dp = new boolean[n + 1][m + 1];
  5. // initialize
  6. dp[0][0] = true;
  7. for (int j = 1; j <= m; j++) {
  8. dp[0][j] = dp[0][j - 1] && p.charAt(j - 1) == '*';
  9. }
  10. for (int i = 1; i <= n; i++) {
  11. for (int j = 1; j <= m; j++) {
  12. if (p.charAt(j - 1) != '*') {
  13. dp[i][j] = dp[i - 1][j - 1] && (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '?');
  14. } else {
  15. dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
  16. }
  17. }
  18. }
  19. return dp[n][m];
  20. }
  21. }